import React, {PureComponent} from "react";
import {Select} from "antd";

import lodash from 'lodash';

const Option = Select.Option;
const OptGroup = Select.OptGroup;

const filter = (input, option) => {
    return option.props.children.toString().toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
        option.props.value.toString().toLowerCase().indexOf(input.toLowerCase()) >= 0;

}

class ListGroupSelector extends PureComponent {
    render() {
        const {
            dataSource = [],
            labelField = "label",
            valueField = "value",
            groupField = "label",
            ...rest
        } = this.props;
        let group_result = lodash.groupBy(dataSource, groupField);
        return (
            <Select
                {...rest}
                style={{width: 180}}
                allowClear={true}
                showSearch
                filterOption={filter}
            >
                {lodash.keys(group_result) &&
                    lodash.keys(group_result).map(key => (
                        <OptGroup label={key}>
                            {group_result[key].map(item => (<Option value={item[valueField]} key={item[labelField]}>
                                {item[labelField]}
                            </Option>))}
                        </OptGroup>
                    ))}
            </Select>
        );
    }
}

export default ListGroupSelector;
